package com.zwh.spring.demo.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages= {"com.zwh.spring.demo.mapper.primary"}, sqlSessionFactoryRef="primarySessionFactory")
public class MyBatisPrimaryConfig {

	@Autowired
	@Qualifier("primaryDataSource")
	private DataSource primaryDataSource;
	
	@Bean
	public SqlSessionFactory primarySessionFactory() throws Exception{
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		factoryBean.setDataSource(primaryDataSource);
		
		return factoryBean.getObject();
	}
	
	@Bean
	public SqlSessionTemplate primarySessionTemplate() throws Exception{
		SqlSessionTemplate template = new SqlSessionTemplate(primarySessionFactory());
		
		return template;
		
	}
	
	@Bean(name="primaryTransectionManager")
	public DataSourceTransactionManager transactionManagers() {
		return new DataSourceTransactionManager(primaryDataSource);
	}
}
